<template>
  <div>
    <!-- 主要内容输入框和搜索重置按钮 -->
    <i-search ref="iSearch" :model="formData" @search="search" @reset="reset">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="formData.userName"></el-input>
      </el-form-item>
      <el-form-item label="用户账号" prop="userAccount">
        <el-input v-model="formData.userAccount"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="formData.role" placeholder="请选择">
          <el-option label="店长" value="2"></el-option>
          <el-option label="管理员" value="1"></el-option>
          <el-option label="超级管理员" value="0" disabled=""></el-option>
          <!-- <el-option label="司机" value="司机"></el-option> -->
        </el-select>
      </el-form-item>
    </i-search>

    <!-- 表格区域 -->
    <i-table
      :toolbar="toolbar"
      :tableData="tableData"
      :pageInfo="pageInfo"
      :selectionShow="true"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <!-- 表头标题区域 -->
      <el-table-column
        v-for="(item,index) in columnList"
        :key="index"
        :label="item.label"
        :prop="item.prop"
        align="center"
      ></el-table-column>
    </i-table>
    <!-- 点击新增按钮后的弹出框 -->
    <!-- @dialog-before-close="dialogBeforeClose" -->
    <i-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      @dialog-before-close= "dialogBeforeClose"
      @dialog-cancel="dialogCancel"
      @dialog-confirm="dialogConfirm"
    >
      <el-form :model="dialogFormData" ref="formRef" :rules="formRules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="userAccount">
              <el-input v-model="dialogFormData.userAccount" placeholder="请输入账号" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="userName">
              <el-input v-model="dialogFormData.userName" placeholder="请输入用户名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="userSex">
              <el-select v-model="dialogFormData.userSex" placeholder="请选择">
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="dialogFormData.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户邮箱" prop="email">
              <el-input v-model="dialogFormData.email" placeholder="请输入用户邮箱"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="idCard">
              <el-input v-model="dialogFormData.idCard" placeholder="请输入身份证号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="dialogFormData.password" placeholder="请输入用户密码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户角色" prop="role">
              <el-select v-model="dialogFormData.role" placeholder="请选择">
                <el-option label="管理员" value="1"></el-option>
                <el-option label="店长" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传头像" prop="picturePath">
              <div class="btn-box">
                点击上传
<input type="file" id="addfile" @change="inputChange($event)" />
              </div>
              <div class="imginfourl">{{this.dialogFormData.picturePath}}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </i-dialog>

    <!-- 修改用户会话框 -->
    <i-dialog
      v-model="ChangedialogVisible"
      :title="ChangedialogTitle"
      @dialog-before-close= "ChangedialogBeforeClose"
      @dialog-cancel="ChangedialogCancel"
      @dialog-confirm="ChangedialogConfirm"
    >
      <el-form
        :model="ChangedialogFormData"
        ref="ChangeformRef"
        :rules="formRules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="userAccount">
              <el-input v-model="ChangedialogFormData.userAccount" placeholder="请输入账号" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="userName">
              <el-input v-model="ChangedialogFormData.userName" placeholder="请输入用户名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="userSex">
              <el-select v-model="ChangedialogFormData.userSex"  placeholder="请选择">
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="ChangedialogFormData.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户邮箱" prop="email">
              <el-input v-model="ChangedialogFormData.email" placeholder="请输入用户邮箱"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="idCard">
              <el-input v-model="ChangedialogFormData.idCard" placeholder="请输入身份证号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传头像" prop="picturePath">
              <div class="btn-box">
                点击修改
<input type="file" id="editfile" @change="editinputChange($event)" />
              </div>
              <div class="imginfourl">{{this.ChangedialogFormData.picturePath}}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </i-dialog>
  </div>
</template>

<script>
// 注意首两个字母要大写，这样才会被识别出来所调用的子组件
import ISearch from "../../components/common/i-search.vue";
import ITable from "../../components/common/i-table.vue";
import IDialog from "../../components/common/i-dialog.vue";
import axios from "axios";
import req from "@/api/user-manager.js";
export default {
  name: "user-manage",
  data() {
     // 自定义验证身份证
    var validateIdCard = (rule, value, callback) => {
      let regIdcard = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/

      console.log('te', regIdcard.test(value))

      if (regIdcard.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入正确的身份证号'))
        this.$message.info('请输入正确的身份证号码')
      }
    }
    return {
      // 用户搜索栏
      formData: {
        userName:'',
        userAccount:''
      },
      // 新增按钮弹出框输入的数据对象
      dialogFormData: {
        userAccount:'',
        userName:'',
        userSex:'',
        phone:"",
        email:"",
        idCard:"",
        password:'',
        role:'',
        picturePath:''
      },
      // 修改用户对话框数据对象
      ChangedialogFormData: {},
      // 设置新增弹出框的默认状态为隐藏
      dialogVisible: false,
      // 设置修改用户信息会话框为默认隐藏
      ChangedialogVisible: false,
      // 存储选中用户信息的id
      multipId: [],
      // 图片上传地址
      addPicInfo: '',
      // 新增按钮的弹出框标题提示
      dialogTitle: "新增用户",
      // 修改会话框的标题
      ChangedialogTitle: "修改用户",
      // 分页数据
      pageInfo: {
        pageIndex: 1,
        pageSize: 5,
        total: 0
      },
      // 表格区域多个按钮数据设置
      toolbar: [
        {
          btnName: "新增",
          type: "primary",
          // 设置按钮的触发事件
          func: () => {
            this.dialogVisible = true;
          }
        },
        {
          btnName: "修改",
          type: "primary",
          // 查询选中用户信息
          func: () => {
            
            // console.log(this.multipId.length)
            if (this.multipId.length === 1) {
              this.ChangedialogVisible = true;
              req("getChangeInfo", {
                userId: this.multipId[0]
              }).then(data => {
                this.ChangedialogFormData = data.data;
                if(data.data.userSex===1){
                  this.ChangedialogFormData.userSex='女'
                }else{
                  this.ChangedialogFormData.userSex='男'
                }
                //  if(data.data.role===1){
                //   this.ChangedialogFormData.role='管理员'
                // }else{
                //   this.ChangedialogFormData.role='店长'
                // }
              });
            }
          }
        },
        {
          btnName: "删除",
          type: "primary",
          func: async () => {
    if(this.multipId.length!==0){
              const confirmResult = await this.$confirm(
              "此操作将永久删除所选用户, 是否继续?",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }
            ).catch(err => err);
            if (confirmResult !== "confirm") {
               this.$message("已取消删除");
              this.fetch();
            } else {
              req("deleteUser", {
                userId: this.multipId.join(",")
              }).then(data => {
                if (data.code !== 0) {
                  this.$message.error(data.msg);
                  this.fetch();
                }
                this.$message.success(data.msg);
                this.fetch();
              });
            }
            }
            
          }
        }
      ],
      // 表格表头数据
      columnList: [
        { label: "账号", prop: "userAccount" },
        { label: "姓名", prop: "userName" },
        { label: "角色", prop: "role" },
        { label: "性别", prop: "userSex" },
        { label: "手机", prop: "phone" },
        { label: "邮箱", prop: "email" },
        { label: "身份证", prop: "idCard" }
      ],
      // 表格内容数据
      tableData: [],
      // 表单验证规则
      formRules: {
        userAccount: [{ required: true, message: "请输入账号", trigger: "change" },],
        userName: [{ required: true, message: "请输入姓名", trigger: "change" },],
        userSex: [{ required: true, message: "请选择性别", trigger: "change" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            min: 5,
            max: 11,
            message: "长度须符合 5 到 11 个字符",
            trigger: "change"
          }
        ],
        // email: [{ required: true, message: "请输入邮箱", trigger: "change" }],
        idCard: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          { validator: validateIdCard, trigger: 'blur' }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          {
            min: 8,
            max: 15,
            message: "长度须符合 8 到 15 个字符",
            trigger: "change"
          }
        ],
        role: [{ required: true, message: "请选择用户角色", trigger: "change" }]
      }
    };
  },
  // 组件挂载完毕之前加载数据
  created() {
      this.fetch()
  },
  methods: {
    inputChange(event) {
      let form = new FormData();
      let file = document.getElementById("addfile").files[0];

      form.append("multipartFile", file, file.name);
      axios({
        method: "post",
        url: "http://120.76.142.108:8080/pc/image/upload",
        data: form,
        headers: {
          "Content-Type": "Multipart/form-data"
        }
      }).then(data => {
        console.log("data", data);
        if(data.data.code === 0){
 this.dialogFormData.picturePath=data.data.data
         this.$notify({
          title: '成功',
          message:data.data.msg,
          type: 'success'
        });
        }else{
          this.$notify({
          title: '失败',
          message:data.data.msg,
          type: 'warning'
        });
        }
       
      });
    },
    editinputChange(event) {
      let form = new FormData();
      let file = document.getElementById("editfile").files[0];

      form.append("multipartFile", file, file.name);
      axios({
        method: "post",
        url: "http://120.76.142.108:8080/pc/image/upload",
        data: form,
        headers: {
          "Content-Type": "Multipart/form-data"
        }
      }).then(data => {
        console.log("data", data);
        if(data.data.code === 0){
this.ChangedialogFormData.picturePath=data.data.data
         this.$notify({
          title: '成功',
          message:'修改图片成功',
          type: 'success'
        });
        }else{
          this.$notify({
          title: '失败',
          message:'修改图片失败',
          type: 'warning'
        });
        }
        
      });
    },
    fetch() {
      this.pageInfo.pageIndex = 1;
      this.pageInfo.pageSize = 5;
      this.search();
    },

    search() {
      req("getTableData", {
        // access_token: JSON.parse(sessionStorage.getItem("userInfo"))
        //   .access_token,
        ...this.formData,
        pageSize: this.pageInfo.pageSize,
        pageNum: this.pageInfo.pageIndex
      }).then(data => {
        console.log(data);
        this.pageInfo.total = data.data.total;
        this.pageInfo.pageSize = data.data.pageSize;
        this.pageInfo.pageNum = data.data.pageNum;
        this.tableData = data.data.list;
        // console.log(this.tableData);
        // 把返回的角色数据替换成对应文字
        this.tableData.forEach(item => {
          if (item.role === 1) {
            item.role = "管理员";
          } else if (item.role === 2) {
            item.role = "店长";
          } else {
            item.role = "超级管理员";
          }
        });
        //     // 把返回的性别信息替换成对应性别
        this.tableData.forEach(item => {
          if (item.userSex === 0) {
            item.userSex = "男";
          } else if (item.userSex === 1) {
            item.userSex = "女";
          }
        });
      });

      // axios({
      //   method:'post',
      //   url:'http://d299o16972.qicp.vip/pc/user/listUser',
      //   data: qs.stringify({
      //   access_token:JSON.parse(sessionStorage.getItem('userInfo')).access_token,
      //     ...this.formData,
      //     pageSize:this.pageInfo.pageSize,
      //     pageNum:this.pageInfo.pageIndex
      //   }),
      //   headers:{
      //     'Content-Type':'application/x-www-form-urlencoded;'
      //   }
      // }).then(data=>{
      //   console.log(data)
      // })
      // console.log("搜索框被点击了");
      // console.log(this.formData);
    },
    reset() {
      this.fetch();
    },
    // 每页多少条数据
    handleSizeChange(value) {
      // console.log(value);
      this.pageInfo.pageSize = value;
      this.search();
    },
    // 当前页码
    handleCurrentChange(value) {
      // console.log(value);
      this.pageInfo.pageIndex = value;
      this.search();
    },
    // 获取选中用户的id
    handleSelectionChange(rows) {
      console.log(rows)
      this.multipId = [];
      rows.forEach(item => {
        this.multipId.push(item.userId);
      });
    },

    // 点击取消隐藏弹出的表单并清空表单数据
    dialogCancel() {
      
      this.$refs.formRef.resetFields();
      this.fetch();
      this.dialogVisible = false;
    },
    // 点击取消隐藏会话框并清空表单
    ChangedialogCancel() {
      
      this.$refs.ChangeformRef.resetFields();
      this.fetch();
      this.ChangedialogVisible = false;
    },
    ChangedialogBeforeClose(){
this.fetch();
      this.$refs.ChangeformRef.resetFields();
      this.ChangedialogVisible = false;
    },
    // 在表单关闭之前刷新页面
    dialogBeforeClose() {
      this.$refs.formRef.resetFields();
      this.fetch();
      this.dialogVisible = false;
    },

    // 点击新增对话框确认按钮新增用户
    dialogConfirm() {
      // 将性别转化为数字
      if (this.dialogFormData.userSex) {
        this.dialogFormData.userSex = parseInt(this.dialogFormData.userSex);
        // console.log(typeof this.dialogFormData.userSex);
      } else {
        console.log("0");
      }
      // 将用户角色转化为数字
      if (this.dialogFormData.role) {
        this.dialogFormData.role = parseInt(this.dialogFormData.role);
        // console.log(typeof this.dialogFormData.role);
      } else {
        console.log("0");
      }
      // console.log(typeof this.dialogFormData.userSex)
      this.$refs.formRef.validate(async valid => {
        if (!valid) return;
        req("addUsers", {
          access_token: JSON.parse(sessionStorage.getItem("userInfo"))
            .access_token,
          ...this.dialogFormData
        }).then(data => {
          console.log(data);
          if (data.code !== 0) {
            return this.$message.error(data.msg);
          } else {
            this.$message.success(data.msg);
          }
          // 隐藏对话框
          this.dialogVisible = false;
          // 刷新页面
          this.fetch();
        });
      });
    },
    // 点击确认按钮修改用户信息
    ChangedialogConfirm() {
      if(this.ChangedialogFormData.userSex === '女'){
        this.ChangedialogFormData.userSex=1
      }else if(this.ChangedialogFormData.userSex==='男'){
        this.ChangedialogFormData.userSex=0
      }
      console.log(this.ChangedialogFormData)
      req("editUserInfo", {
        ...this.ChangedialogFormData,
        userId: this.multipId[0]
      }).then(data => {
        // console.log(data)
        if(data.code===0){
this.$message.success(data.msg);
          this.fetch();
          this.ChangedialogVisible = false;
        }else{
          this.$message.error(data.msg);
        }
      });
    },
  },
  // 子组件注册
  components: {
    ISearch,
    ITable,
    IDialog
  }
};
</script>

<style lang="scss" scoped>
.columnLenght {
  width: 300px;
}
.el-input{
  width: 218px;
}

</style>
